#include <iostream>
#include <queue>
#include <cstdlib>
using namespace std;

template <typename T>
class CStack
{
public:
    CStack(void){}
    ~CStack(void){}

    int size();
    bool empty();
    void push(const T & node);
    T top();
    void pop();

private:
    queue<T> queue1;
    queue<T> queue2;
};

template<typename T>
int CStack<T>::size()
{
    return queue1.size() + queue2.size();
}

template<typename T>
bool CStack<T>::empty()
{
    return 0 == size();
}

template<typename T>
void CStack<T>::push(const T& node)
{
    if (!queue2.empty())
        queue2.push(node);
    else
        queue1.push(node);
}

template<typename T>
T CStack<T>::top()
{
    T node;
    if (!queue1.empty())
    {
        while(queue1.size() > 1)
        {
            node = queue1.front();
            queue2.push(node);
            queue1.pop();
        }
        node = queue1.front();
        queue2.push(node);
        queue1.pop();
    }
    else if (!queue2.empty())
    {
        while(queue2.size() > 1)
        {
            node = queue2.front();
            queue1.push(node);
            queue2.pop();
        }
        node = queue2.front();
        queue1.push(node);
        queue2.pop();
    }
    else
    {
        cout << "Stack is empty!" << endl;
        exit(0);
    }
    return node;
}

template<typename T>
void CStack<T>::pop()
{
    T node;
    if (!queue1.empty())
    {
        while(queue1.size() > 1)
        {
            node = queue1.front();
            queue2.push(node);
            queue1.pop();
        }
        node = queue1.front();
        queue1.pop();
    }
    else if (!queue2.empty())
    {
        while(queue2.size() > 1)
        {
            node = queue2.front();
            queue1.push(node);
            queue2.pop();
        }
        node = queue2.front();
        queue2.pop();
    }
    else
    {
        cout << "Stack is empty!" << endl;
        exit(0);
    }
}
int main(int argc, char * argv[])
{
    CStack<int> stack;
    stack.push(1);
    stack.push(2);
    cout << stack.top() << endl;
    stack.push(3);
    stack.push(4);
    cout << stack.top() << endl;
    stack.pop();
    stack.push(5);
    cout << stack.top() << endl;
    stack.pop();
    cout << stack.top() << endl;
    cout << stack.top() << endl;
    cout << stack.top() << endl;
    stack.pop();
    cout << stack.top() << endl;
    return 0;
}
